package com.bw.seckill_module.seckilllist;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bw.common.field.EventBusEntity;
import com.bw.common.mvvm.view.BaseActivity;
import com.bw.seckill_module.BR;
import com.bw.seckill_module.R;
import com.bw.seckill_module.databinding.ActivitySeckillBinding;
import com.bw.seckill_module.service.SecKillService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

@Route(path = "/seckill/seckilllistactivity")
public class SecKillListActivity extends BaseActivity<ActivitySeckillBinding,SecKillListViewModel> {

    private SecKillService secKillService;

    @Override
    public int bindLayout() {
        return R.layout.activity_seckill;
    }

    @Override
    public int vrId() {
        return BR.vm;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribeSecKill(EventBusEntity entity){
        if (entity.action.equals("secTime")){
            long time = secKillService.getTime();
            vm.time = time;
            vm.secKill();
        }else if (entity.action.equals("startTimmer")){
            long time = (long) entity.data.get("time");
            Intent intent = new Intent(this, SecKillService.class);
            intent.putExtra("time",time);
            startService(intent);
            Intent bindIntent = new Intent(this,SecKillService.class);
            bindService(bindIntent,connection,BIND_AUTO_CREATE);
        }
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            SecKillService.TimeBind timeBind = (SecKillService.TimeBind) service;
            secKillService = timeBind.getSecKillService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unbindService(connection);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Intent bindIntent = new Intent(this,SecKillService.class);
        bindService(bindIntent,connection,BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Intent intent = new Intent(this, SecKillService.class);
        stopService(intent);
    }
}
